<!DOCTYPE html>
<html>

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>员工列表</title>


    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">

    <link rel="stylesheet" href="../plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../plugins/ionicons/css/ionicons.min.css">
    <link rel="stylesheet" href="../plugins/iCheck/square/blue.css">
    <link rel="stylesheet" href="../plugins/morris/morris.css">
    <link rel="stylesheet" href="../plugins/jvectormap/jquery-jvectormap-1.2.2.css">
    <link rel="stylesheet" href="../plugins/datepicker/datepicker3.css">
    <link rel="stylesheet" href="../plugins/daterangepicker/daterangepicker.css">
    <link rel="stylesheet" href="../plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
    <link rel="stylesheet" href="../plugins/datatables/dataTables.bootstrap.css">
    <link rel="stylesheet" href="../plugins/treeTable/jquery.treetable.css">
    <link rel="stylesheet" href="../plugins/treeTable/jquery.treetable.theme.default.css">
    <link rel="stylesheet" href="../plugins/select2/select2.css">
    <link rel="stylesheet" href="../plugins/colorpicker/bootstrap-colorpicker.min.css">
    <link rel="stylesheet" href="../plugins/bootstrap-markdown/css/bootstrap-markdown.min.css">
    <link rel="stylesheet" href="../plugins/adminLTE/css/AdminLTE.css">
    <link rel="stylesheet" href="../plugins/adminLTE/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <link rel="stylesheet" href="../plugins/ionslider/ion.rangeSlider.css">
    <link rel="stylesheet" href="../plugins/ionslider/ion.rangeSlider.skinNice.css">
    <link rel="stylesheet" href="../plugins/bootstrap-slider/slider.css">
    <link rel="stylesheet" href="../plugins/bootstrap-datetimepicker/bootstrap-datetimepicker.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="../js/jwt-decode.js"></script>

    <style>
        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 40px;
            height: 10px;
        }

        .toggle-switch input {
            display: none;
        }

        .toggle-switch label {
            position: absolute;
            width: 100%;
            height: 100%;
            background-color: #ccc;
            border-radius: 34px;
            cursor: pointer;
        }

        .toggle-switch label:before {
            content: "";
            position: absolute;
            top: 2px;
            left: 2px;
            width: 20px;
            height: 20px;
            background-color: #fff;
            border-radius: 50%;
            transition: transform 0.2s;
        }

        .toggle-switch input:checked+label {
            background-color: #2196F3;
        }

        .toggle-switch input:checked+label:before {
            transform: translateX(30px);
        }
    </style>
</head>

<body class="hold-transition skin-purple sidebar-mini">

    <div class="wrapper">

        <!-- 页面头部 -->
        <header class="main-header">

            <!-- Logo -->
            <a href="common-index.html" class="logo">
                <!-- 侧边栏迷你logo，尺寸为50x50像素 -->
                <span class="logo-mini"><b>电子钱包</b></span>
                <!-- 常规状态和移动设备的logo -->
                <span class="logo-lg"><b>电子钱包</b>后台管理</span>
            </a>

            <!-- 头部导航栏：样式可以在header.less中找到 -->
            <nav class="navbar navbar-static-top">
                <!-- 侧边栏切换按钮 -->
                <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
                    <span class="sr-only">Toggle navigation</span>
                </a>

                <div class="navbar-custom-menu">
                    <ul class="nav navbar-nav">

                        <li class="dropdown user user-menu">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                                <img src="" class="user-image all-avatar-image">
                                <span class="hidden-xs employee-name"></span>
                            </a>

                            <ul class="dropdown-menu">
                                <!-- 用户图片 -->
                                <li class="user-header">
                                    <img src="" class="img-circle all-avatar-image">

                                    <p class="employee-name"></p>
                                </li>

                                <li class="user-footer">
                                    <div class="pull-left">
                                        <a href="employee-info.html" class="btn btn-default btn-flat">修改信息</a>
                                    </div>
                                    <div class="pull-right">
                                        <a href="javascript:void(0);" class="btn btn-default btn-flat"
                                            id="logoutBtn">退出账号</a>
                                    </div>
                                </li>
                            </ul>
                        </li>

                    </ul>
                </div>
            </nav>
        </header>
        <!-- 页面头部 /-->

        <!-- 导航侧栏 -->
        <aside class="main-sidebar">
            <!-- 侧边栏：样式可以在sidebar.less中找到 -->
            <section class="sidebar">
                <!-- 侧边栏用户面板 -->
                <div class="user-panel">
                    <div class="pull-left image">
                        <img src="" class="img-circle all-avatar-image">
                    </div>
                    <div class="pull-left info">
                        <p class="employee-name"></p>
                        <a href="#"><i class="fa fa-circle text-success"></i> 在线</a>
                    </div>
                </div>

                <ul class="sidebar-menu">
                    <li class="header">菜单</li>

                    <li id="admin-index"><a href="common-index.html"><i class="fa fa-dashboard"></i> <span>首页</span></a>
                    </li>

                    <!-- 菜单 -->

                    <li class="treeview">
                        <a href="#">
                            <i class="fa fa-folder"></i>
                            <span>系统管理</span>
                            <span class="pull-right-container">
                                <i class="fa fa-angle-left pull-right"></i>
                            </span>
                        </a>
                        <ul class="treeview-menu">

                            <li id="admin-role-manage">
                                <a href="role-list.html">
                                    <i class="fa fa-circle-o"></i> 角色管理
                                </a>
                            </li>

                            <li id="admin-datalist">
                                <a href="employee-list.html">
                                    <i class="fa fa-circle-o"></i> 员工管理
                                </a>
                            </li>

                            <li id="admin-user-manage">
                                <a href="user-list.html">
                                    <i class="fa fa-circle-o"></i> 用户管理
                                </a>
                            </li>

                            <li id="admin-profile">
                                <a href="employee-info.html">
                                    <i class="fa fa-circle-o"></i> 个人中心
                                </a>
                            </li>

                        </ul>
                    </li>



                    <li class="treeview">
                        <a href="#">
                            <i class="fa fa-pie-chart"></i> <span>业务管理</span>
                            <span class="pull-right-container">
                                <i class="fa fa-angle-left pull-right"></i>
                            </span>
                        </a>
                        <ul class="treeview-menu">

                            <li id="history-list">
                                <a href="history-list.html">
                                    <i class="fa fa-circle-o"></i> 历史记录管理
                                </a>
                            </li>

                        </ul>
                    </li>

                </ul>
            </section>

        </aside>
        <!-- 导航侧栏 /-->

        <div class="content-wrapper">

            <!-- 内容头部 -->
            <section class="content-header">
                <h1>
                    员工管理
                    <small>员工列表</small>
                </h1>
                <ol class="breadcrumb">
                    <li><a href="#"><i class="fa fa-dashboard"></i> 首页</a></li>
                    <li><a href="#">员工管理</a></li>
                    <li class="active">员工列表</li>
                </ol>
            </section>
            <!-- 内容头部 /-->

            <!-- 正文区域 -->
            <section class="content">

                <!-- .box-body -->
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">列表</h3>
                    </div>

                    <div class="box-body">

                        <!-- 数据表格 -->
                        <div class="table-box">

                            <!--工具栏-->
                            <div class="pull-left">
                                <div class="form-group form-inline">
                                    <div class="btn-group">
                                        <button type="button" id="newButton" class="btn btn-default" title="新建"><i
                                                class="fa fa-user-plus"></i> 新增员工</button>
                                    </div>
                                </div>
                            </div>

                            <div class="row head">
                                <div class="col-lg-2 box-tools pull-right" style="width: 230px;">
                                    <div class="input-group">
                                        <input type="text" class="form-control" placeholder="手机号" id="search-input"
                                            maxlength="11">
                                        <span class="input-group-btn">
                                            <button class="btn btn-info" type="button" id="search-button"><span
                                                    class="glyphicon glyphicon-search"></span></button>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <!--工具栏/-->

                            <!--数据列表-->
                            <table id="dataList" class="table table-bordered table-striped table-hover dataTable">
                                <thead>
                                    <tr>
                                        <!-- <th class="" style="padding-right:0px;">
                                            <input id="selall" type="checkbox" class="icheckbox_square-blue">
                                        </th> -->
                                        <th class="">序号</th>
                                        <th class="">姓名</th>
                                        <th class="sorting_asc_disabled">员工号</th>
                                        <th class="sorting_desc_disabled">员工电话</th>
                                        <th class="">电子邮箱</th>
                                        <th class="">生日</th>
                                        <th class="">性别</th>
                                        <th class="">角色</th>
                                        <th class="">在职情况</th>
                                        <th class="text-center">操作</th>
                                    </tr>
                                </thead>
                                <tbody id="dataBody">

                                </tbody>

                            </table>
                            <!--数据列表/-->
                        </div>
                        <!-- 数据表格 /-->


                    </div>
                    <!-- /.box-body -->

                    <!-- .box-footer-->
                    <div class="box-footer">
                        <div class="pull-left">
                            <div class="form-group form-inline" style="margin: 25px 0px 20px 0px;">
                                <span></span>
                            </div>

                        </div>
                        <div id="back-button" style="text-align:center;"></div>
                        <div class="box-tools pull-right">
                            <ul class="pagination">

                            </ul>
                        </div>

                    </div>
                    <!-- /.box-footer-->

                </div>
                <!-- Modal -->
                <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                    data-backdrop="false">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                        aria-hidden="true" id="close_state">&times;</span></button>
                                <h4 class="modal-title" id="myModalLabel">提示</h4>
                            </div>
                            <div class="modal-body">

                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal"
                                    id="del_state">取消</button>
                                <button type="button" class="btn btn-primary" data-dismiss="modal"
                                    id="confirm_state">确认</button>
                            </div>
                        </div>
                    </div>
                </div>

            </section>
            <!-- 正文区域 /-->


        </div>

        <script>

            // 顶部与侧边栏信息渲染,注销按钮
            $(document).ready(function () {
                var token = localStorage.getItem('token');
                var longToken = localStorage.getItem('longToken');

                // 获取注销按钮
                var logoutBtn = $("#logoutBtn");

                // 为注销按钮添加点击事件
                logoutBtn.click(function () {
                    // 清除本地存储的 token 和 longToken
                    localStorage.removeItem('token');
                    localStorage.removeItem('longToken');
                    // 跳转到登录
                    window.location.href = 'employee-login.html';
                });

                if (token && longToken) {
                    var decoded = jwt_decode(longToken);
                    var userId = decoded.userId;

                    getInfo(userId, token, longToken);
                } else {
                    // 跳转到登录页面
                    window.location.href = 'employee-login.html';
                }
            });

            // 获取个人数据，渲染侧边栏和头部
            function getInfo(userId, token, longToken) {
                var url = 'http://localhost:8080/employee/findByIdController?userId=' + userId;

                if (token && longToken) {
                    url += '&token=' + token + '&longToken=' + longToken;
                }

                // 发送 AJAX 请求获取数据
                $.ajax({
                    url: url,
                    method: 'get',
                    success: function (result) {

                        if (result.code === 200) {
                            var datas = result.datas;
                            var imageUrl = "http://localhost:8080/" + datas.imageAddress;

                            var imgs = document.querySelectorAll('img.all-avatar-image');
                            imgs.forEach(function (img) {
                                img.src = imageUrl;
                            });

                            var elements = document.querySelectorAll('.employee-name');
                            elements.forEach(function (el) {
                                el.innerHTML = datas.userName;
                            });

                        } else if (result.code === 6000 || result.code === 4000) {
                            // 跳转到登录
                            window.location.href = 'employee-login.html';
                        } else {
                            alert("获取数据失败");
                        }

                    },
                    error: function (xhr, status, error) {
                        console.log("请求失败");
                    }
                });
            }

            // 获取数据
            function getPageInfo(currentPageNumber) {
                if (currentPageNumber <= 1) {
                    currentPageNumber = 1;
                }

                var token = localStorage.getItem('token');
                var longToken = localStorage.getItem('longToken');

                var url = 'http://localhost:8080/employee/findPageController?currentPageNumber=' + currentPageNumber;

                if (token && longToken) {
                    url += '&token=' + token + '&longToken=' + longToken;
                }

                // 发送 AJAX 请求获取数据
                $.ajax({
                    url: url,
                    method: 'get',
                    success: function (result) {
                        if (result.code == 200) {
                            var dataList = result.datas.datas;
                            var dataBody = $("#dataBody");

                            $("#back-button").empty();

                            dataBody.empty();

                            $(".pull-left").show();

                            // 遍历数据列表，生成表格行
                            for (var i = 0; i < dataList.length; i++) {
                                (function () { // 使用立即执行函数创建新的作用域
                                    var employee = dataList[i];

                                    var tr = $("<tr></tr>");
                                    tr.append("<td>" + ((currentPageNumber - 1) * 10 + i + 1) + "</td>");
                                    tr.append("<td>" + employee.userName + "</td>");
                                    tr.append("<td>" + employee.employeeAccount + "</td>");
                                    tr.append("<td>" + employee.phone + "</td>");
                                    tr.append("<td>" + employee.email + "</td>");
                                    tr.append("<td>" + formatDate(employee.borndate) + "</td>");
                                    tr.append("<td>" + employee.gender + "</td>");
                                    var roleNames = [];
                                    if (employee.roles) {
                                        roleNames = employee.roles.map(function (role) {
                                            return role.roleName;
                                        });
                                    }
                                    tr.append("<td>" + roleNames.join(', ') + "</td>");

                                    var roleIds = [];
                                    if (employee.roles) {
                                        roleIds = employee.roles.map(function (role) {
                                            return role.roleId;
                                        });
                                    }
                                    var switchStatus = "";

                                    if (roleIds.includes(5)) {
                                        switchStatus = "";
                                    } else {
                                        switchStatus = "checked";
                                    }


                                    tr.append('<td class="toggle-switch"><input type="checkbox" data-toggle="modal" data-target="#myModal" id="switch-' + employee.userId + '"' + switchStatus + '><label for="switch-' + employee.userId + '"></label></td>');

                                    tr.append("<td class='text-center'>" +
                                        "<button type='button' class='btn bg-olive btn-xs' id ='employee_details_" + employee.userId + "'>详情</button> " +
                                        // "<button type='button' class='btn bg-olive btn-xs'>修改</button> " +
                                        "<button type='button' class='btn bg-olive btn-xs' id ='employee_assign_" + employee.userId + "'>分配角色</button> " +
                                        "</td>");

                                    dataBody.append(tr);

                                    checkEmployeeDetailsPermission(employee.userId, employee.roles); // 详情按钮权限判断
                                    checkEmployeeAssignPermission(employee.userId, employee.roles); // 分配角色

                                    // 缓存选择器的结果
                                    var switchSelector = $('#switch-' + employee.userId);

                                    var flag = true;

                                    // 绑定开关按钮的点击事件处理程序
                                    switchSelector.off('click').on('click', function () {
                                        var hasPermission = false;

                                        if (token && longToken) {
                                            var decoded = jwt_decode(longToken);
                                            var roles = decoded.roles;
                                        } else {
                                            // 跳转到登录页面
                                            window.location.href = 'employee-login.html';
                                        }

                                        // 将 hasPermission 的值设置为 false
                                        hasPermission = false;

                                        // 判断当前用户的角色
                                        var currentUserRole = '';
                                        for (var i = 0; i < roles.length; i++) {
                                            var role = roles[i];

                                            if (role.roleId === 1) { // 超级管理员
                                                currentUserRole = 'superAdmin';
                                                hasPermission = true;
                                                break;
                                            } else if (role.roleId === 2) {
                                                currentUserRole = 'admin';
                                                for (var j = 0; j < role.permissions.length; j++) {
                                                    var permission = role.permissions[j];
                                                    if (permission.permissionId === 2) {
                                                        hasPermission = true;
                                                        break;
                                                    }
                                                }
                                                if (hasPermission) {
                                                    break;
                                                }
                                            } else {
                                                for (var j = 0; j < role.permissions.length; j++) {
                                                    var permission = role.permissions[j];
                                                    if (permission.permissionId === 2) {
                                                        hasPermission = true;
                                                        break;
                                                    }
                                                }
                                                if (hasPermission) {
                                                    break;
                                                }
                                            }
                                        }


                                        // 验证是否有权限
                                        if (hasPermission) {
                                            var isChecked = switchSelector.prop('checked');

                                            if (token && longToken) {
                                                var decoded = jwt_decode(longToken);
                                                var employee_userId = decoded.userId;
                                            } else {
                                                // 跳转到登录页面
                                                window.location.href = 'employee-login.html';
                                            }
                                            var userId_now = employee.userId; // 获取当前被点击的员工的 userId

                                            var hasRole1 = false;

                                            getUserData(userId_now, token, longToken)
                                                .then(function (data) {
                                                    var roleIdList = data.roleIdList;
                                                    for (var i = 0; i < roleIdList.length; i++) {

                                                        if (roleIdList.indexOf(1) === 1) {

                                                            hasRole1 = true;
                                                            break;
                                                        }
                                                    }

                                                    // 判断当前用户是否为要操作的员工本人
                                                    if (employee_userId == userId_now) {
                                                        $('#myModalLabel').text('提示');
                                                        $('#myModal .modal-body').text('不能修改自己的状态');
                                                        $('#del_state').hide();
                                                        $('#close_state').hide();
                                                        // 取消开关按钮的选中状态
                                                        switchSelector.prop('checked', !switchSelector.prop('checked'));
                                                        flag = false;
                                                    } else if (hasRole1) {
                                                        $('#myModalLabel').text('提示');
                                                        $('#myModal .modal-body').text('不能修改超级管理员的状态');
                                                        $('#del_state').hide();
                                                        $('#close_state').hide();
                                                        // 取消开关按钮的选中状态
                                                        switchSelector.prop('checked', !switchSelector.prop('checked'));
                                                        flag = false;
                                                    } else if (currentUserRole === 'admin' && (roleIdList.indexOf(2) === 0)) {
                                                        $('#myModalLabel').text('提示');
                                                        $('#myModal .modal-body').text('不能修改管理员的账号');
                                                        $('#del_state').hide();
                                                        $('#close_state').hide();
                                                        // 取消开关按钮的选中状态
                                                        switchSelector.prop('checked', !switchSelector.prop('checked'));
                                                        flag = false;
                                                    } else {
                                                        $('#del_state').show();
                                                        $('#close_state').show();
                                                        if (isChecked) {
                                                            $('#myModalLabel').text('提示');
                                                            $('#myModal .modal-body').text('是否要启用该员工');
                                                        } else {
                                                            $('#myModalLabel').text('提示');
                                                            $('#myModal .modal-body').text('是否要禁用该员工');
                                                        }
                                                    }
                                                })
                                                .catch(function (error) {
                                                    window.location.href = 'common-404.html';
                                                });

                                            // 设置确认按钮的 ID
                                            $('#confirm_state').attr('data-employee-id', employee.userId);
                                            // 设置取消按钮
                                            $('#del_state').attr('data-employee-id', employee.userId);
                                            $('#close_state').attr('data-employee-id', employee.userId);

                                            // 绑定确认按钮的点击事件处理程序
                                            $('#confirm_state').off('click').on('click', function () {
                                                var userId = $(this).attr('data-employee-id');
                                                var isChecked = switchSelector.prop('checked');
                                                if (isChecked) {

                                                    switchSelector.prop('checked', true);
                                                    // 从禁用到启用时

                                                    if (flag) {
                                                        window.location.href = 'employee-role.html?userId=' + userId;
                                                    }



                                                } else {
                                                    switchSelector.prop('checked', false);

                                                    if (!(token && longToken)) {
                                                        // 跳转到登录页面
                                                        window.location.href = 'employee-login.html';
                                                    }

                                                    // 如果用户没有权限，则不发起请求
                                                    if (!hasPermission) {
                                                        return;
                                                    }
                                                    var employeeId = employee.employeeId;
                                                    // 从启用到禁用时调用的方法
                                                    updateEmployeeStatus(employeeId, userId, ['5', '6'], token, longToken, currentPageNumber);

                                                }
                                            });
                                        } else {
                                            $('#del_state').hide();
                                            $('#close_state').hide();
                                            // 没有权限，提示用户
                                            $('#myModalLabel').text('提示');
                                            $('#myModal .modal-body').text('您没有权限进行此操作，请联系管理员获取权限');
                                            $('#del_state').hide();
                                            $('#close_state').hide();
                                            // 取消开关按钮的选中状态
                                            switchSelector.prop('checked', !switchSelector.prop('checked'));
                                        }

                                    });

                                    // 绑定取消按钮的点击事件处理程序
                                    $('#del_state').off('click').on('click', function () {
                                        var userId = $(this).attr('data-employee-id');
                                        var switchBtn = $('#switch-' + userId);
                                        switchBtn.prop('checked', !switchBtn.prop('checked'));
                                    });

                                    // 绑定关闭按钮的点击事件处理程序
                                    $('#close_state').off('click').on('click', function () {
                                        var userId = $(this).attr('data-employee-id');
                                        var switchBtn = $('#switch-' + userId);
                                        switchBtn.prop('checked', !switchBtn.prop('checked'));
                                    });

                                })();
                            }


                            var pagination = $(".pagination");
                            pagination.empty();
                            pagination.append("<li><a href='javascript:void(0);' aria-label='Previous' onclick='getPageInfo(1)'>首页</a></li>");
                            pagination.append("<li><a href='javascript:void(0);' onclick='getPageInfo(" + (currentPageNumber - 1) + ")'>上一页</a></li>");

                            // 生成页码
                            let startPage = 1;
                            let endPage = result.datas.totalPageNumber;

                            // 如果总页数超过5页，则固定显示5个页码
                            if (endPage > 5) {
                                if (currentPageNumber <= 3) {
                                    endPage = 5;
                                } else if (currentPageNumber >= endPage - 2) {
                                    startPage = endPage - 4;
                                } else {
                                    startPage = currentPageNumber - 2;
                                    endPage = currentPageNumber + 2;
                                }
                            }

                            // 生成页码
                            for (let i = startPage; i <= endPage; i++) {
                                let pageTag = $("<li><a href='javascript:void(0);' onclick='getPageInfo(" + i + ")'>" + i + "</a></li>");

                                // 添加 active 类到当前页码
                                if (i === currentPageNumber) {
                                    pageTag.find("a").css({
                                        "background-color": "#a9a9a9",
                                        "color": "#fff"
                                    });
                                }

                                pagination.append(pageTag);
                            }

                            if (currentPageNumber >= result.datas.totalPageNumber) {
                                currentPageNumber = result.datas.totalPageNumber - 1;
                            }

                            pagination.append("<li><a href='javascript:void(0);' onclick='getPageInfo(" + (currentPageNumber + 1) + ")'>下一页</a></li>");
                            pagination.append("<li><a href='javascript:void(0);' aria-label='Next' onclick='getPageInfo(" + (result.datas.totalPageNumber) + ")'>尾页</a></li>");

                            var pageInfo = $(".form-group.form-inline span");
                            pageInfo.empty();
                            pageInfo.text("总共" + result.datas.totalPageNumber + "页，共" + result.datas.totalRecords + "条数据");


                        } else if (result.code === 6000 || 4000) {
                            // 跳转到登录
                            window.location.href = 'employee-login.html';
                        } else {
                            alert("获取数据失败");
                        }
                    },
                    error: function (xhr, status, error) {
                        console.log("请求失败");
                    }
                });
            }

            // 格式化日期
            function formatDate(date) {
                var formattedDate = new Date(date);
                var year = formattedDate.getFullYear();
                var month = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
                var day = ("0" + formattedDate.getDate()).slice(-2);
                return year + "-" + month + "-" + day;
            }

            // 页面加载完成后调用获取数据函数
            $(document).ready(function () {

                getPageInfo(1);

                $('#search-button').click(function () {
                    var searchValue = document.getElementById("search-input").value; // 搜索框里面的值

                    var token = localStorage.getItem('token');
                    var longToken = localStorage.getItem('longToken');

                    if (token && longToken) {
                        if (searchValue != null) {

                            getEmployeeByLoginAccount(searchValue, token, longToken);
                        } else {

                        }
                    } else {
                        // 跳转到登录
                        window.location.href = 'employee-login.html';
                    }

                });
            });

            // 跳转到新增员工界面
            $(document).ready(function () {
                var newButton = $("#newButton");
                var token = localStorage.getItem('token');
                var longToken = localStorage.getItem('longToken');

                if (token && longToken) {
                    var decoded = jwt_decode(longToken);
                    var roles = decoded.roles;
                } else {
                    // 跳转到登录页面
                    window.location.href = 'employee-login.html';
                }

                // 将 hasPermission 的值设置为 false
                var hasPermission = false;

                for (var i = 0; i < roles.length; i++) {
                    var role = roles[i];
                    for (var j = 0; j < role.permissions.length; j++) {
                        var permission = role.permissions[j];

                        if (permission.permissionId == 1) { // 新增员工权限
                            hasPermission = true;
                            break;
                        }
                    }
                    if (hasPermission) {
                        break;
                    }
                }

                if (hasPermission) {
                    newButton.on("click", function () {
                        window.location.href = "employee-add.html";
                    });
                } else {
                    newButton.prop("disabled", true);
                }
            });

            // 从启用到禁用时调用的方法
            function updateEmployeeStatus(employeeId, userId, roles, token, longToken, currentPageNumber) {
                // 将数据转换为JSON格式的字符串
                var data = JSON.stringify({
                    employeeId: employeeId,
                    userId: userId,
                    roles: roles
                });
                $.ajax({
                    url: 'http://localhost:8080/employee/updateRoleController?token=' + token + '&longToken=' + longToken,
                    type: 'POST',
                    data: data,
                    contentType: 'application/json',
                    success: function (result) {
                        if (result.code === 200) {
                            // 更新成功，更新前端页面显示
                            getPageInfo(currentPageNumber);
                        } else if (result.code === 4000) {
                            // 跳转到登录
                            window.location.href = 'employee-login.html';
                        } else {
                            // 更新失败，弹出错误提示
                            alert(result.msg);
                        }
                    },
                    error: function () { // 请求失败的回调函数
                        alert('请求失败，请稍后重试！');
                    }
                });
            }

            // 详情按钮权限判断
            function checkEmployeeDetailsPermission(userId, roleList) {
                var token = localStorage.getItem('token');
                var longToken = localStorage.getItem('longToken');

                if (token && longToken) {
                    var decoded = jwt_decode(longToken);
                    var roles = decoded.roles;

                } else {
                    // 跳转到登录页面
                    window.location.href = 'employee-login.html';
                }

                var detailsButton = $("#employee_details_" + userId);

                // 将 hasDetails 的值设置为 false
                var hasDetails = false;

                for (var i = 0; i < roles.length; i++) {
                    var role = roles[i];

                    var hasRole5 = false;
                    for (var j = 0; j < roleList.length; j++) {
                        if (roleList[j].roleId === 5) {
                            hasRole5 = true;
                            break;
                        }
                    }

                    if (hasRole5) { // 如果角色 ID 包含在指定的角色列表中，则禁用
                        detailsButton.prop("disabled", true);
                        return;
                    }

                    var hasPermission6 = false;
                    for (var j = 0; j < role.permissions.length; j++) {
                        var permission = role.permissions[j];

                        if (permission.permissionId == 3) { // 查看详情权限
                            hasPermission6 = true;
                            break;
                        }
                    }

                    if (hasPermission6) {
                        hasDetails = true;
                        break;
                    }
                }

                if (hasDetails) {
                    detailsButton.prop("disabled", false);
                    detailsButton.click(function () {
                        window.location.href = 'employee-desc.html?userId=' + userId;
                    });
                } else {
                    detailsButton.prop("disabled", true);
                }


            }

            // 分配角色按钮权限判断
            function checkEmployeeAssignPermission(userId, roleList) {
                var token = localStorage.getItem('token');
                var longToken = localStorage.getItem('longToken');

                if (token && longToken) {
                    var decoded = jwt_decode(longToken);
                    var roles = decoded.roles;
                    var loginId = decoded.userId;
                } else {
                    // 跳转到登录页面
                    window.location.href = 'employee-login.html';
                }

                var AssignButton = $("#employee_assign_" + userId);

                // 将 hasDetails 的值设置为 false
                var hasDetails = false;

                if (loginId === userId) { // 如果登录用户 ID 与传入的用户 ID 相同，则禁用分配角色按钮
                    AssignButton.prop("disabled", true);
                    return;
                }

                for (var i = 0; i < roles.length; i++) {
                    var role = roles[i];

                    var hasRole5 = false;
                    for (var j = 0; j < roleList.length; j++) {
                        if (roleList[j].roleId === 5 || roleList[j].roleId === 1) {
                            hasRole5 = true;
                            break;
                        }
                    }

                    if (hasRole5) { // 如果角色 ID 包含在指定的角色列表中，则禁用分配角色按钮
                        AssignButton.prop("disabled", true);
                        return;
                    }

                    var hasPermission6 = false;
                    for (var j = 0; j < role.permissions.length; j++) {
                        var permission = role.permissions[j];

                        if (permission.permissionId == 6) { // 分配角色权限
                            hasPermission6 = true;
                            break;
                        }
                    }

                    if (hasPermission6) {
                        hasDetails = true;
                        break;
                    }
                }

                if (hasDetails) {
                    AssignButton.prop("disabled", false);
                    AssignButton.click(function () {
                        window.location.href = 'employee-role.html?userId=' + userId;
                    });
                } else {
                    AssignButton.prop("disabled", true);
                }
            }

            // 根据账号查询员工信息
            function getEmployeeByLoginAccount(loginAccount, token, longToken) {
                $.ajax({
                    url: 'http://localhost:8080/employee/findByLoginAccountController?loginAccount=' + loginAccount + '&token=' + token + '&longToken=' + longToken,
                    type: 'GET',
                    success: function (result) {
                        if (result.code === 200) {
                            $("#dataBody").empty();
                            $(".pagination").empty();
                            $(".pull-left").hide();
                            $("#back-button").empty();

                            var employee = result.datas;

                            var dataBody = $("#dataBody");

                            var tr = $("<tr></tr>");
                            tr.append("<td>" + 1 + "</td>");
                            tr.append("<td>" + employee.userName + "</td>");
                            tr.append("<td>" + employee.employeeAccount + "</td>");
                            tr.append("<td>" + employee.phone + "</td>");
                            tr.append("<td>" + employee.email + "</td>");
                            tr.append("<td>" + formatDate(employee.borndate) + "</td>");
                            tr.append("<td>" + employee.gender + "</td>");
                            var roleNames = [];
                            var roleIds = [];

                            if (employee.roles) {
                                employee.roles.forEach(function (role) {
                                    if (role.roleId !== 6) { // 过滤掉角色 ID 为 6 的角色
                                        roleNames.push(role.roleName);
                                        roleIds.push(role.roleId);
                                    }
                                });
                            }

                            tr.append("<td>" + roleNames.join(', ') + "</td>");

                            var switchStatus = roleIds.includes(5) ? "" : "checked";


                            tr.append('<td class="toggle-switch"><input type="checkbox" data-toggle="modal" data-target="#myModal" id="switch-' + employee.userId + '"' + switchStatus + '><label for="switch-' + employee.userId + '"></label></td>');

                            tr.append("<td class='text-center'>" +
                                "<button type='button' class='btn bg-olive btn-xs' id ='employee_details_" + employee.userId + "'>详情</button> " +
                                "<button type='button' class='btn bg-olive btn-xs' id ='employee_assign_" + employee.userId + "'>分配角色</button> " +
                                "</td>");

                            dataBody.append(tr);

                            checkEmployeeDetailsPermission(employee.userId, employee.roles); // 详情按钮权限判断
                            checkEmployeeAssignPermission(employee.userId, employee.roles); // 分配角色

                            // 缓存选择器的结果
                            var switchSelector = $('#switch-' + employee.userId);

                            var flag = true;

                            // 绑定开关按钮的点击事件处理程序
                            switchSelector.off('click').on('click', function () {
                                var hasPermission = false;

                                if (token && longToken) {
                                    var decoded = jwt_decode(longToken);
                                    var roles = decoded.roles;
                                } else {
                                    // 跳转到登录页面
                                    window.location.href = 'employee-login.html';
                                }

                                // 将 hasPermission 的值设置为 false
                                hasPermission = false;

                                // 判断当前用户的角色
                                var currentUserRole = '';
                                for (var i = 0; i < roles.length; i++) {
                                    var role = roles[i];

                                    if (role.roleId === 1) { // 超级管理员
                                        currentUserRole = 'superAdmin';
                                        hasPermission = true;
                                        break;
                                    } else if (role.roleId === 2) {
                                        currentUserRole = 'admin';
                                        for (var j = 0; j < role.permissions.length; j++) {
                                            var permission = role.permissions[j];
                                            if (permission.permissionId === 2) {
                                                hasPermission = true;
                                                break;
                                            }
                                        }
                                        if (hasPermission) {
                                            break;
                                        }
                                    } else {
                                        for (var j = 0; j < role.permissions.length; j++) {
                                            var permission = role.permissions[j];
                                            if (permission.permissionId === 2) {
                                                hasPermission = true;
                                                break;
                                            }
                                        }
                                        if (hasPermission) {
                                            break;
                                        }
                                    }
                                }


                                // 验证是否有权限
                                if (hasPermission) {
                                    var isChecked = switchSelector.prop('checked');

                                    if (token && longToken) {
                                        var decoded = jwt_decode(longToken);
                                        var employee_userId = decoded.userId;
                                    } else {
                                        // 跳转到登录页面
                                        window.location.href = 'employee-login.html';
                                    }
                                    var userId_now = employee.userId; // 获取当前被点击的员工的 userId

                                    var hasRole1 = false;

                                    getUserData(userId_now, token, longToken)
                                        .then(function (data) {
                                            var roleIdList = data.roleIdList;
                                            for (var i = 0; i < roleIdList.length; i++) {

                                                if (roleIdList.indexOf(1) === 1) {

                                                    hasRole1 = true;
                                                    break;
                                                }
                                            }

                                            // 判断当前用户是否为要操作的员工本人
                                            if (employee_userId == userId_now) {
                                                $('#myModalLabel').text('提示');
                                                $('#myModal .modal-body').text('不能修改自己的状态');
                                                $('#del_state').hide();
                                                $('#close_state').hide();
                                                // 取消开关按钮的选中状态
                                                switchSelector.prop('checked', !switchSelector.prop('checked'));
                                                flag = false;
                                            } else if (hasRole1) {
                                                $('#myModalLabel').text('提示');
                                                $('#myModal .modal-body').text('不能修改超级管理员的状态');
                                                $('#del_state').hide();
                                                $('#close_state').hide();
                                                // 取消开关按钮的选中状态
                                                switchSelector.prop('checked', !switchSelector.prop('checked'));
                                                flag = false;
                                            } else if (currentUserRole === 'admin' && (roleIdList.indexOf(2) === 0)) {
                                                $('#myModalLabel').text('提示');
                                                $('#myModal .modal-body').text('不能修改管理员的账号');
                                                $('#del_state').hide();
                                                $('#close_state').hide();
                                                // 取消开关按钮的选中状态
                                                switchSelector.prop('checked', !switchSelector.prop('checked'));
                                                flag = false;
                                            } else {
                                                $('#del_state').show();
                                                $('#close_state').show();
                                                if (isChecked) {
                                                    $('#myModalLabel').text('提示');
                                                    $('#myModal .modal-body').text('是否要启用该员工');
                                                } else {
                                                    $('#myModalLabel').text('提示');
                                                    $('#myModal .modal-body').text('是否要禁用该员工');
                                                }
                                            }
                                        })
                                        .catch(function (error) {
                                            window.location.href = 'common-404.html';
                                        });

                                    // 设置确认按钮的 ID
                                    $('#confirm_state').attr('data-employee-id', employee.userId);
                                    // 设置取消按钮
                                    $('#del_state').attr('data-employee-id', employee.userId);
                                    $('#close_state').attr('data-employee-id', employee.userId);

                                    // 绑定确认按钮的点击事件处理程序
                                    $('#confirm_state').off('click').on('click', function () {
                                        var userId = $(this).attr('data-employee-id');
                                        var isChecked = switchSelector.prop('checked');
                                        if (isChecked) {

                                            switchSelector.prop('checked', true);
                                            // 从禁用到启用时

                                            if (flag) {
                                                window.location.href = 'employee-role.html?userId=' + userId;
                                            }



                                        } else {
                                            switchSelector.prop('checked', false);

                                            if (!(token && longToken)) {
                                                // 跳转到登录页面
                                                window.location.href = 'employee-login.html';
                                            }

                                            // 如果用户没有权限，则不发起请求
                                            if (!hasPermission) {
                                                return;
                                            }
                                            var employeeId = employee.employeeId;
                                            // 从启用到禁用时调用的方法
                                            updateEmployeeStatus(employeeId, userId, ['5', '6'], token, longToken, 1);

                                        }
                                    });
                                } else {
                                    $('#del_state').hide();
                                    $('#close_state').hide();
                                    // 没有权限，提示用户
                                    $('#myModalLabel').text('提示');
                                    $('#myModal .modal-body').text('您没有权限进行此操作，请联系管理员获取权限');
                                    $('#del_state').hide();
                                    $('#close_state').hide();
                                    // 取消开关按钮的选中状态
                                    switchSelector.prop('checked', !switchSelector.prop('checked'));
                                }

                            });

                            // 绑定取消按钮的点击事件处理程序
                            $('#del_state').off('click').on('click', function () {
                                var userId = $(this).attr('data-employee-id');
                                var switchBtn = $('#switch-' + userId);
                                switchBtn.prop('checked', !switchBtn.prop('checked'));
                            });

                            // 绑定关闭按钮的点击事件处理程序
                            $('#close_state').off('click').on('click', function () {
                                var userId = $(this).attr('data-employee-id');
                                var switchBtn = $('#switch-' + userId);
                                switchBtn.prop('checked', !switchBtn.prop('checked'));
                            });
                            var backButton = $('<button class="btn btn-default">返回</button>');
                            backButton.on('click', function () {
                                getPageInfo(1);
                            });

                            var centerDiv = $("#back-button");
                            centerDiv.append(backButton);

                            $('.box-footer').append(centerDiv);

                        } else if (result.code === 4000) {
                            // 跳转到登录
                            window.location.href = 'employee-login.html';
                        } else {

                            // 更新失败，弹出错误提示
                            alert(result.msg);
                        }
                    },
                    error: function () { // 请求失败的回调函数
                        alert('请求失败，请稍后重试！');
                    }
                });
            }

            // 根据userId获取当前用户的角色
            function getUserData(userId, token, longToken) {
                return new Promise(function (resolve, reject) {
                    $.ajax({
                        url: 'http://localhost:8080/user/findByIdController?userId=' + userId + "&token=" + token + '&longToken=' + longToken,
                        type: 'GET',
                        success: function (result) {
                            // 处理获取到的数据
                            if (result.code == 200) {
                                var roleList = result.datas.roles;
                                var employeeId = result.datas.employeeId; // 获取employee_id

                                // 定义一个 Set 对象，用于存储所有的角色 ID
                                var roleIdSet = new Set();

                                // 遍历角色列表，将所有角色 ID 添加到 Set 中
                                for (var i = 0; i < roleList.length; i++) {
                                    var role = roleList[i];
                                    roleIdSet.add(role.roleId);
                                }

                                // 将 Set 转换成数组，即可得到所有不重复的角色 ID
                                var roleIdList = Array.from(roleIdSet);

                                resolve({ roleIdList: roleIdList, employeeId: employeeId }); // 返回roleIdList和employeeId

                            } else if (result.code == 4000) {
                                // 跳转到登录页面
                                window.location.href = 'employee-login.html';
                            } else {
                                window.location.href = 'common-404.html';
                            }
                        },
                        error: function (xhr, status, error) {
                            console.log("请求失败");
                        }
                    });
                });
            }




        </script>



        <!-- 底部导航 -->
        <footer class="main-footer">
            <strong>Copyright &copy; <a href="">电子钱包</a>.</strong> All rights reserved.
        </footer>
        <!-- 底部导航 /-->

    </div>


    <script src="../plugins/jQuery/jquery-2.2.3.min.js"></script>
    <script src="../plugins/jQueryUI/jquery-ui.min.js"></script>
    <script>
        $.widget.bridge('uibutton', $.ui.button);
    </script>
    <script src="../plugins/bootstrap/js/bootstrap.min.js"></script>
    <script src="../plugins/raphael/raphael-min.js"></script>
    <script src="../plugins/morris/morris.min.js"></script>
    <script src="../plugins/sparkline/jquery.sparkline.min.js"></script>
    <script src="../plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
    <script src="../plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
    <script src="../plugins/knob/jquery.knob.js"></script>
    <script src="../plugins/daterangepicker/moment.min.js"></script>
    <script src="../plugins/daterangepicker/daterangepicker.js"></script>
    <script src="../plugins/daterangepicker/daterangepicker.zh-CN.js"></script>
    <script src="../plugins/datepicker/bootstrap-datepicker.js"></script>
    <script src="../plugins/datepicker/locales/bootstrap-datepicker.zh-CN.js"></script>
    <script src="../plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
    <script src="../plugins/slimScroll/jquery.slimscroll.min.js"></script>
    <script src="../plugins/fastclick/fastclick.js"></script>
    <script src="../plugins/iCheck/icheck.min.js"></script>
    <script src="../plugins/adminLTE/js/app.min.js"></script>
    <script src="../plugins/treeTable/jquery.treetable.js"></script>
    <script src="../plugins/select2/select2.full.min.js"></script>
    <script src="../plugins/colorpicker/bootstrap-colorpicker.min.js"></script>
    <script src="../plugins/bootstrap-wysihtml5/bootstrap-wysihtml5.zh-CN.js"></script>
    <script src="../plugins/bootstrap-markdown/js/bootstrap-markdown.js"></script>
    <script src="../plugins/bootstrap-markdown/locale/bootstrap-markdown.zh.js"></script>
    <script src="../plugins/bootstrap-markdown/js/markdown.js"></script>
    <script src="../plugins/bootstrap-markdown/js/to-markdown.js"></script>
    <script src="../plugins/ckeditor/ckeditor.js"></script>
    <script src="../plugins/input-mask/jquery.inputmask.js"></script>
    <script src="../plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
    <script src="../plugins/input-mask/jquery.inputmask.extensions.js"></script>
    <script src="../plugins/datatables/jquery.dataTables.min.js"></script>
    <script src="../plugins/datatables/dataTables.bootstrap.min.js"></script>
    <script src="../plugins/chartjs/Chart.min.js"></script>
    <script src="../plugins/flot/jquery.flot.min.js"></script>
    <script src="../plugins/flot/jquery.flot.resize.min.js"></script>
    <script src="../plugins/flot/jquery.flot.pie.min.js"></script>
    <script src="../plugins/flot/jquery.flot.categories.min.js"></script>
    <script src="../plugins/ionslider/ion.rangeSlider.min.js"></script>
    <script src="../plugins/bootstrap-slider/bootstrap-slider.js"></script>
    <script src="../plugins/bootstrap-datetimepicker/bootstrap-datetimepicker.js"></script>
    <script src="../plugins/bootstrap-datetimepicker/locales/bootstrap-datetimepicker.zh-CN.js"></script>
    <script>
        $(document).ready(function () {
            // 选择框
            $(".select2").select2();

            // WYSIHTML5编辑器
            $(".textarea").wysihtml5({
                locale: 'zh-CN'
            });
        });


        // 设置激活菜单
        function setSidebarActive(tagUri) {
            var liObj = $("#" + tagUri);
            if (liObj.length > 0) {
                liObj.parent().parent().addClass("active");
                liObj.addClass("active");
            }
        }


        $(document).ready(function () {

            // 激活导航位置
            setSidebarActive("admin-datalist");

            // 列表按钮 
            $("#dataList td input[type='checkbox']").iCheck({
                checkboxClass: 'icheckbox_square-blue',
                increaseArea: '20%'
            });
            // 全选操作 
            $("#selall").click(function () {
                var clicks = $(this).is(':checked');
                if (!clicks) {
                    $("#dataList td input[type='checkbox']").iCheck("uncheck");
                } else {
                    $("#dataList td input[type='checkbox']").iCheck("check");
                }
                $(this).data("clicks", !clicks);
            });
        });
    </script>
</body>

</html>